package com.lxp.service.impl;

import com.lxp.service.EmailService;
import com.lxp.servicebase.exception.MyException;
import com.lxp.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class  EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RedisTemplate<String,String> template;//redis工具类

    //发送邮件
    @Override
    public void sendEmail(String userEmail) {
        if (StringUtils.isEmpty(userEmail)){
            throw new MyException(20001,"验证码错误");
        }

        String from="178028404@qq.com";//自己的邮箱地址
        String subject="[小皮在线教育]";
        //获取四位随机码
        String code =RandomUtil.getFourBitRandom();
        //将用户的邮箱以及验证码存入redis中并设置有效时间为5分钟
        template.opsForValue().set(userEmail,code,5, TimeUnit.MINUTES);
        String text = "您正在注册小皮在线教育账号,验证码为:"+code
                +",此验证码五分钟有效!\n[小皮教育]";
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject(subject);
        message.setFrom(from);
        message.setTo(userEmail);
        message.setText(text);
        mailSender.send(message);
    }
}
